# ActsAsBlast
module Setwave  #:nodoc:
  module Acts  #:nodoc:
    module Blast  #:nodoc:
      def self.included(base)
        base.extend(ClassMethods)
      end
      
      module ClassMethods
        def acts_as_blast()
          attr_accessor :recipients, :failed_recipients, :blast
          include InstanceMethods
        end
      end
      
      module InstanceMethods        
        
        # save one blast per recipient for this user.
        # this method is only accessible from a user model since "self" refs user props
        # returns boolean if pass/fail
        def blast!(recipients, blast)
          # check => if parent class == User
          return false unless self.kind_of? User  
          blast.user_id = self.id

          if blast.from.nil?
            blast.from = self.email
          else
            blast.from = (valid_email(blast.from)) ? blast.from : "#{blast.from} <#{self.email}>"
          end
          
          @blast = blast
          recipient_list(recipients)
          save_blasts()
          return true
        end

        private
        # parse the recipients for the blast and make sure each email address is valid...        
        def recipient_list(r)
          @recipients = []
          @failed_recipients = []
          r.gsub(",", " ").split(" ").each do |a|
            a.strip!
            if valid_email(a)
              @recipients << a
            else
              @failed_recipients << a
            end
          end
        end

       # clone the original blast and save a new one per recipient
       # created_at and sent_at will have the same times. email isn't actually sent until you run the rake task
       def save_blasts
         for recipient in @recipients
          blast = @blast.clone()
          blast.to = recipient
          now = Time.now()
          blast.created_at = now
          blast.sent_at = now
          blast.save!
         end
       end
       
       def valid_email(email)
          if email =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
            return true
          else
            return false
          end
       end
       
      end
    end
  end
end